//
//  MANoteDetailViewController.m
//  meiang_edu
//
//  Created by 栋 on 2018/12/31.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//


#import "MANoteDetailViewController.h"
#import "MANoteDetailHeader.h"
#import "MANoteReplyCell.h"
#import "MAAlertView.h"
#import "MARightTipView.h"
@interface MANoteDetailViewController ()<UITableViewDelegate,UITableViewDataSource,MANoteReplyCellProtocol,MANoteDetailHeaderProtocol>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/**
 数据源;回复数组
 */
@property (nonatomic ,strong) NSMutableArray<MANoteReplyModel *> * dataSource;
/**
 header数据 详情
 */
@property (nonatomic ,strong) MANoteManageModel * msgDetailmodel;
/**
 上一页传入的数据
 */
@property (nonatomic ,strong) MANoteManageModel * manageModel;
/**
 回复cell 用于计算高度
 */
@property (nonatomic ,strong) MANoteReplyCell * cellCalculate;
/**
 header  message详情
 */
@property (nonatomic ,strong) MANoteDetailHeader * msgDetailCell;


@end

@implementation MANoteDetailViewController

#pragma mark - 初始化

+(instancetype)messageDetailViewControllerWith:(MANoteManageModel *)manageModel{
    MANoteDetailViewController * messageVC = [MANoteDetailViewController new];
    messageVC.manageModel = manageModel;
    return messageVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpNav];
    [self setUpTableView];
}

- (void)setUpTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"MANoteReplyCell" bundle:nil] forCellReuseIdentifier:@"MANoteReplyCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
}

- (void)setUpNav{
    self.title = [NSString stringWithFormat:@"%@详情",self.funcItemModel.corner_name];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(tapRightItem) image:@"reminderbutton_logo" highImage:@"Exclamation point"];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)tapRightItem{
    [MARightTipView showWithTips:@"如果您需要删除或停用卡片内容,请长按您所需要操作的卡片"];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_tableView.mj_header beginRefreshing];
}

#pragma mark - 懒加载
- (MANoteReplyCell *)cellCalculate{
    if (!_cellCalculate) {
        _cellCalculate = [[[NSBundle mainBundle] loadNibNamed:@"MANoteReplyCell" owner:nil options:nil] lastObject];
    }
    return _cellCalculate;
}

- (MANoteDetailHeader *)msgDetailCell{
    if (!_msgDetailCell) {
        _msgDetailCell = [[[NSBundle mainBundle] loadNibNamed:@"MANoteDetailHeader" owner:nil options:nil] lastObject];
        _msgDetailCell.delegate = self;
        if ([self.funcItemModel.corner_name isEqualToString:@"活动"]) {
            _msgDetailCell.viewReNotice.hidden = YES;
            _msgDetailCell.lblNoticeCount.text = @"报名情况统计";
        }
        _msgDetailCell.lblType.hidden = YES;
        _msgDetailCell.imgType.hidden = YES;
    }
    return _msgDetailCell;
}

#pragma mark - 网络请求
//header请求
- (void)headerRefresh{
    [self requestData:YES];
}
//footer请求----未使用
- (void)footerRefresh{
    [self requestData:NO];
}

- (void)requestData:(BOOL)new{
    __block NSInteger totoal = 0;
    dispatch_group_t group = dispatch_group_create();
    if (new) {
        totoal ++;
        dispatch_group_enter(group);
        [self requestHeader:^{
            dispatch_group_leave(group);
        }];
    }
    dispatch_group_enter(group);
    [self requestList:new completion:^{
        dispatch_group_leave(group);
    }];
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"dispatch_group_notify");
        [self.tableView reloadData];
        if (new) {
            [self.tableView.mj_header endRefreshing];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
    });
}

//获取回复列表数据
- (void)requestList:(BOOL)new completion:(void(^)(void))completion{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",MESSAGE_GET_REVERT,_manageModel.keyid];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            _dataSource = [NSMutableArray array];
            NSArray *arrayMessages = dataDict[@"value"];
            for (NSDictionary * dictMessage in arrayMessages) {
                MANoteReplyModel * model = [MANoteReplyModel mj_objectWithKeyValues:dictMessage];
                model.cellHeight = [self.cellCalculate cellHeightWithModel:model];
                [self.dataSource addObject:model];
            }
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
        
    } failure:^(NSError *error) {
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        completion();
    }];
}

//获取header数据
- (void)requestHeader:(void(^)(void))completion{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",MESSAGE_DETAIL,_manageModel.keyid];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"dataDict = %@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            self.msgDetailmodel = [MANoteManageModel mj_objectWithKeyValues:dataDict[@"value"]];
            [self.msgDetailCell setDataWithModel:self.msgDetailmodel];
            if ([self.funcItemModel.corner_name isEqualToString:@"活动"]) {
                _msgDetailCell.viewReNotice.hidden = YES;
                _msgDetailCell.lblNoticeCount.text = @"报名情况统计";
            }
            self.tableView.tableHeaderView = self.msgDetailCell;
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        completion();
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MANoteReplyCell * cell =[tableView dequeueReusableCellWithIdentifier:@"MANoteReplyCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    [cell setDataWithModel:self.dataSource[indexPath.row]indexPath:indexPath delegate:self];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.dataSource[indexPath.row].cellHeight;
}

#pragma mark - MANoteReplyCellProtocol
//点击删除消息
- (void)msgReplyCellDidTapDelete:(MANoteReplyCell *)cell indexPath:(NSIndexPath *)indexPath{
    MANoteReplyModel * replyModel = self.dataSource[indexPath.row];
    [MAAlertView showAlertViewWithMessage:@"确定要删除这条消息吗?" MakeSureBlock:^{
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"keyid"] = replyModel.keyid;
        [MANetwork POST:[NSString stringWithFormat:@"%@%@",DETAIL_MESSAGE_DELETE,replyModel.keyid] parameters:parameters autoShowFailAlert:YES showLoading:YES success:^(id response, BOOL success) {
            if (success) {
                [self.tableView.mj_header beginRefreshing];
                [MBManager showBriefAlert:@"删除成功"];
            }
        } failure:^(NSError *error) {
            
        }];
    } cancelBlock:^{
        
    }];
}

#pragma mark - MANoteDetailHeaderProtocol
//点击header上的删除
- (void)noteDetailHeaderDidTapDelete:(MANoteDetailHeader *)cell model:(MANoteManageModel *)model{
    [MAAlertView showAlertViewWithMessage:@"您确定删除当前消息?" MakeSureBlock:^{
        [MANetwork POSTString:DELETE_MESSAGE bodyString:model.keyid autoShowFailAlert:YES showLoading:YES success:^(id response, BOOL success) {
            if (success) {
                [self.navigationController popViewControllerAnimated:YES];
                [MBManager showBriefAlert:@"删除成功"];
            }
        } failure:^(NSError *error) {
            
        }];
    } cancelBlock:^{
        
    }];
}


@end
